﻿using System;
using System.ComponentModel.DataAnnotations;
using System.Web;
using System.Web.Profile;
using System.Web.Security;
using Baggr.ClientSite.Models;
using FeedReader;

namespace Baggr.ClientSite.Controllers
{
    using System.Web.Mvc;
    using System.Linq;

    /// <summary>
    /// Контроллер чтения новостей.
    /// </summary>
    public class ReaderController : Controller
    {
        private FeedDataContext _FeedDataContext;

        private User _UserData;

        [Authorize]
        protected override void  Initialize(System.Web.Routing.RequestContext requestContext)
        {
            base.Initialize(requestContext);
            if (User.Identity.IsAuthenticated)
            {
                _FeedDataContext = new FeedDataContext();
                _FeedDataContext.Connection.Open();
                _UserData = FeedDataContext.Users.SingleOrDefault(curr => curr.UserName == User.Identity.Name);
                if (UserData == null)
                    throw new HttpException(203, "Пользователь не найден");
            }

        }

        public FeedDataContext FeedDataContext
        {
            get
            {
                return _FeedDataContext;
            }
        }

        public User UserData
        {
            get
            {
                return _UserData;
            }
        }
        /// <summary>
        /// Главная страница.
        /// </summary>
        /// <returns>
        /// Главная страница.
        /// </returns>
        [Authorize, HttpGet]
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// Получить
        /// </summary>
        /// <returns></returns>
        [Authorize, HttpGet]
        public ActionResult GetSubscriptions()
        {
            var fodlersModel = new FeedsTree(UserData.Folder);
            return Json(fodlersModel.ToJson(), JsonRequestBehavior.AllowGet);
        }

        [Authorize, HttpGet]
        public ActionResult GetFeedItems(
            Guid feedId,
            string filter,
            string sorting)
        {
            var filterValue = HttpContext.Profile.UpdateProfile(
                "FeedItemsFilter",
                FeedItemsFilter.Parse(filter));

            var sortingValue = HttpContext.Profile.UpdateProfile(
                "FeedItemsSorting",
                FeedItemsSorting.Parse(sorting));

            var feed = FeedDataContext.Feeds.Where(curr => curr.Id == feedId).Single();
            var feedModel = new FilteredAndSortedFeed(FeedDataContext, UserData, feed, filterValue, sortingValue);
            return PartialView("FeedItemList", feedModel);
        }

        protected override void Dispose(bool disposing)
        {
            if (_FeedDataContext != null)
            {
                _FeedDataContext.Connection.Close();
                _FeedDataContext.Dispose();
                _FeedDataContext = null;
            }
        }

        /// <summary>
        /// Set up reting to feed by user.
        /// </summary>
        /// <param name="feedItemId">
        /// Identifier of feed item.
        /// </param>
        /// <param name="rate">
        /// Rating of feedItem.
        /// </param>
        [HttpPost, Authorize]
        public void Rate(Guid feedItemId, short? rate)
        {
            if (rate < 0 || rate > 5)
                throw new HttpException(400, "Рейтинг находится вне диапазана");
            _FeedDataContext.SetFeedItemRate(User.Identity.Name, feedItemId, rate ?? 0);
        }

        /// <summary>
        /// Mark feed item read by user.
        /// </summary>
        [HttpPost, Authorize]
        public void MarkRead(Guid feedItemId)
        {
            _FeedDataContext.MarkFeedItemRead(User.Identity.Name, feedItemId);
        }

        [Authorize, HttpPost]
        public JsonResult AddFodler(Folder folder)
        {
            if(!ModelState.IsValid)
                throw new HttpException("Параметры не верны.");
            folder.Id = Guid.NewGuid();
            UserData.Folder.Folders.Add(folder);
            FeedDataContext.SubmitChanges();
            return Json(new {id = folder.Id});
        }

        public void AddFeed(Subscription subscription)
        {
            if (!ModelState.IsValid)
                throw new HttpException("Параметры не верны.");

            FeedDataContext.Subscribe(subscription.FolderId, subscription.Url);
        }
    }
}
